﻿using System;
using System.Collections;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Configuration;
using CRMEntity;
using CRMFramework;

using Newtonsoft.Json;
using MessageMedia;
using MessageMedia.Common;
using MessageMedia.Diagnostics;
using MessageMedia.Events;
using MessageMedia.Exceptions;
using MessageMedia.Gateway.ActionResult;
using MessageMedia.SMS;


namespace CRMBiz
{
    public static class ContactFollowUpHandler
    {
        static string loanEmailAccount = null;
        static string bussinessEmailAccount = null;
        static string loanEmailAccountPassword = null;
        static string bussinessEmailAccountPassword = null;

        static string personalEmailSubject = null;
        static string businessEmailSubject = null;
        static string maxfundingEmailSubject = null;

        static string personalEmailContent = null;
        static string businessEmailContent = null;
        static string maxfundingEmailContent = null;

        static string MorganFinance_smsUser = null;
        static string MorganFinance_smsPassword = null;
        static string MaxFunding_smsUser = null;
        static string MaxFunding_smsPassword = null;
        static string maxFinance_smsUser = null;
        static string maxFinance_smsPassword = null;

        static string personalSMSContent = null;
        static string businessSMSContent = null;
        static string maxfundingSMSContent = null;

        static string maxfundingEmailAccount = null;
        static string maxfundingEmailAccountPassword = null;

        static string maxfinanceEmailAccount = null;
        static string maxfinanceEmailContent = null;
        static string maxfinanceSMSContent = null;
        static string maxfinanceEmailSubject = null;
        static string maxfinanceEmailAccountPassword = null;

        static string morganFinanceSMTP = null;
       // static string morganFinanceBusinessSMTP = null;
        static string maxFundingSMTP = null;
        static string maxFinanceSMTP = null;

        /// <summary>
        /// Set up default value for sending following up email.
        /// </summary>
        public static void Setup()
        {
            loanEmailAccount = ConfigurationManager.AppSettings["personalLoanEmailAccount"];
            bussinessEmailAccount = ConfigurationManager.AppSettings["bussinessLoanEmailAccount"];
            loanEmailAccountPassword = GetEmailAccountPassword(loanEmailAccount, out morganFinanceSMTP);
            bussinessEmailAccountPassword = GetEmailAccountPassword(bussinessEmailAccount, out morganFinanceSMTP);
            maxfundingEmailAccount = ConfigurationManager.AppSettings["maxfundingLoanEmailAccount"];
            maxfundingEmailAccountPassword = GetEmailAccountPassword(maxfundingEmailAccount, out maxFundingSMTP);

            personalEmailContent = GetEmailTemplate("sp_GetFollowUpEmailContent", out businessEmailContent, out maxfundingEmailContent, out personalEmailSubject, out businessEmailSubject, out maxfundingEmailSubject, out maxfinanceEmailContent, out maxfinanceEmailSubject);
            personalSMSContent = GetSMSTemplate("sp_GetFollowUpSMSContent", out businessSMSContent, out maxfundingSMSContent, out maxfinanceSMSContent);

            MorganFinance_smsUser = ConfigurationManager.AppSettings["MorganFinance_SMSUserName"];
            MorganFinance_smsPassword = ConfigurationManager.AppSettings["MorganFinance_SMSPassword"];
            MaxFunding_smsUser = ConfigurationManager.AppSettings["MAXFunding_SMSUserName"];
            MaxFunding_smsPassword = ConfigurationManager.AppSettings["MAXFunding_SMSPassword"];

            maxfinanceEmailAccount = ConfigurationManager.AppSettings["maxfinanceLoanEmailAccount"];
            maxfinanceEmailAccountPassword = GetEmailAccountPassword(maxfinanceEmailAccount, out maxFinanceSMTP);
            maxFinance_smsUser = ConfigurationManager.AppSettings["MAXFinance_SMSUserName"];
            maxFinance_smsPassword = ConfigurationManager.AppSettings["MAXFinance_SMSPassword"];
        }
        /// <summary>
        /// Get follow up contacts list
        /// </summary>
        /// <returns></returns>
        public static List<FollowUpContact> GetFollowUpList()
        {
            DataTable dt = null;
            FollowUpContact c = null;
            List<FollowUpContact> followUpList = new List<FollowUpContact>();

            dt = DBhelper.ExecuteDatasetSP("sp_GetFollowUpContactList").Tables[0];

            foreach (DataRow dr in dt.Rows)
            {
                c = new FollowUpContact();
                c.ApplicationId = Convert.ToInt32(dr["ApplicationId"].ToString().Trim());
                c.ContactId = Convert.ToInt32(dr["ContactId"].ToString().Trim());
                c.EmailAddress = dr["EmailAddress"].ToString();
                c.MobileNumber = dr["MobileNumber"].ToString().Replace(" ", string.Empty);
                c.FirstName = dr["FirstName"].ToString();
                c.MiddleName = dr["MiddleName"].ToString();
                c.Surname = dr["Surname"].ToString();
                c.ApplicationSource = dr["ApplicationSource"].ToString();
                c.IsBusiness = Convert.ToInt16(dr["isBusiness"].ToString().Trim()) == 1;
                followUpList.Add(c);
            }

            return followUpList;
        }
        /// <summary>
        /// Send Follow up Email to client email address
        /// </summary>
        /// <param name="contactFollowUpList"></param>
        public static void SendEmail(FollowUpContact c)
        {
            string sendFrom = loanEmailAccount;
            string emailContent = personalEmailContent;
            string smsContent = personalSMSContent;
            string emailSubject = personalEmailSubject;
            string emailAccountPassword = loanEmailAccountPassword;
            string sendingName = "Morgan Finance";
            string smtpServerName = morganFinanceSMTP;

            if (c.ApplicationSource == "MaxFunding")
            {
                sendingName = "Max Funding";
                sendFrom = maxfundingEmailAccount;
                emailContent = maxfundingEmailContent;
                smsContent = maxfundingSMSContent;
                emailSubject = maxfundingEmailSubject;
                emailAccountPassword = maxfundingEmailAccountPassword;
                smtpServerName = maxFundingSMTP;
            }
            else if (c.ApplicationSource == "MaxFinance")
            {
                sendingName = "Max Finance";
                sendFrom = maxfinanceEmailAccount;
                emailContent = maxfinanceEmailContent;
                smsContent = maxfinanceSMSContent;
                emailSubject = maxfinanceEmailSubject;
                emailAccountPassword = maxfinanceEmailAccountPassword;
                smtpServerName = maxFinanceSMTP;
            }
            else
            {
                if (c.IsBusiness) // Morgan Finance Business Loan
                {
                    sendFrom = bussinessEmailAccount;
                    emailContent = businessEmailContent;
                    smsContent = businessSMSContent;
                    emailSubject = businessEmailSubject;
                    emailAccountPassword = bussinessEmailAccountPassword;
                }
            }

            string decodeEmailContent = HttpUtility.UrlDecode(emailContent).Replace("%FirstName (Client)%", c.FullName);
            ClientProfileHandler.SendEmail(sendFrom, smtpServerName, sendingName, emailAccountPassword, c.EmailAddress, "", "", emailSubject, decodeEmailContent);
            string emailContentWithName = emailContent.Replace("%25FirstName%20(Client)%25", c.FirstName);
            UpdateApplicationStatus(c, emailContentWithName, false);
        }


        /// <summary>
        /// Send sms to client mobile number
        /// </summary>
        public static string SendMessage(FollowUpContact c)
        {
            string smsContent = personalSMSContent;
            string mobileNumber = c.MobileNumber.Trim().Replace(" ", string.Empty);
            string smsUser = MorganFinance_smsUser;
            string smsPassword = MorganFinance_smsPassword;
            string smsSendingResult = null;

            if (c.ApplicationSource == "MaxFunding")
            {
                smsContent = maxfundingSMSContent;
                smsUser = MaxFunding_smsUser;
                smsPassword = MaxFunding_smsPassword;
            }
            else if (c.ApplicationSource == "MaxFinance")
            {
                smsContent = maxfinanceSMSContent;
                smsUser = maxFinance_smsUser;
                smsPassword = maxFinance_smsPassword;
            }
            else
            {
                if (c.IsBusiness)
                {
                    smsContent = businessSMSContent;
                }
            }

            string messageContent = smsContent.Replace("%FirstName (Client)%", c.FullName);
            smsSendingResult = ConsoleSMSHelper.SendSMS(mobileNumber, messageContent, smsUser, smsPassword);
            UpdateApplicationStatus(c, messageContent, true);
            return smsSendingResult;
        }


        /// <summary>
        /// Update application status after sending follow up email is successful
        /// </summary>
        /// <param name="applicationId"></param>
        private static void UpdateApplicationStatus(FollowUpContact c, string emailContent, bool isSMS)
        {
            string actionTitle = isSMS ? "SMS Sent" : "Email Sent";

            string currentDate = DateTime.Now.ToString("MM/dd/yyyy");
            // string currentDate = "01/31/2014";
            string currentTime = DateTime.Now.ToString("HH:mm:ss");

            HistoryInfo objHistory = new HistoryInfo();
            objHistory.appID = c.ApplicationId;
            objHistory.action = actionTitle;
            objHistory.historyDate = currentDate;
            objHistory.historyTime = DateTime.Now.ToString("HH:mm:ss");
            objHistory.oprator = "System";
            objHistory.description = emailContent;

            bool isRecordHistory = HistoryHandler.AddHistory(objHistory);
            string queryString = "update crm_application set app_result='1.3 Await documents - NO Follow (Case Hold)', editdate='" + DateTime.Now.ToString("yyyy-MM-dd") + " " + currentTime + "' where app_id='" + c.ApplicationId + "'";
            DBhelper.ExecuteNonQuery(queryString);
        }
        /// <summary>
        /// Get password from email account.
        /// </summary>
        /// <returns></returns>
        private static string GetEmailAccountPassword(string emailAccount,out string smtpServerName)
        {
            string sql = "SELECT Password ,EmailId, SMTPserver FROM `crm_emailaccount` WHERE EmailId like '%" + emailAccount + "%'";
            DataTable dt = DBhelper.ExecuteDataset(sql).Tables[0];
            smtpServerName = dt.Rows[0]["SMTPserver"].ToString();
            return dt.Rows[0]["Password"].ToString();
        }
        /// <summary>
        /// Get follow up email content and subject title
        /// </summary>
        /// <param name="storeProcedureName"></param>
        /// <param name="emailSubject"></param>
        /// <returns></returns>
        private static string GetEmailTemplate(string storeProcedureName, out string businessEmailContent, out string maxFundingEmailContent, out string personalEmailSubject, out string businessEmailSubject, out string maxFundingEmailSubject, out string maxFinanceEmailContent, out string maxFinanceEmailSubject)
        {
            string personalEmailContent = null;
            personalEmailSubject = string.Empty;
            businessEmailSubject = string.Empty;
            businessEmailContent = string.Empty;
            maxFundingEmailContent = string.Empty;
            maxFundingEmailSubject = string.Empty;

            DataTable dt = DBhelper.ExecuteDatasetSP(storeProcedureName).Tables[0];
            personalEmailContent = dt.Rows[0]["TemplateFormat"].ToString();
            personalEmailSubject = dt.Rows[0]["emailSubject"].ToString();
            businessEmailContent = dt.Rows[1]["TemplateFormat"].ToString();
            businessEmailSubject = dt.Rows[1]["emailSubject"].ToString();
            maxFundingEmailContent = dt.Rows[2]["TemplateFormat"].ToString();
            maxFundingEmailSubject = dt.Rows[2]["emailSubject"].ToString();

            maxFinanceEmailContent = dt.Rows[3]["TemplateFormat"].ToString();
            maxFinanceEmailSubject = dt.Rows[3]["emailSubject"].ToString();

            return personalEmailContent;
        }
        /// <summary>
        /// Get SMS Template content
        /// </summary>
        /// <param name="storeProcedureName"></param>
        /// <param name="businessSMSContent"></param>
        /// <returns></returns>
        private static string GetSMSTemplate(string storeProcedureName, out string businessSMSContent, out string maxFundingSMSContent, out string maxFinanceSMSContent)
        {
            string personalSMSContent = null;
            businessSMSContent = string.Empty;
            maxFundingSMSContent = string.Empty;

            DataTable dt = DBhelper.ExecuteDatasetSP(storeProcedureName).Tables[0];
            personalSMSContent = dt.Rows[0]["TemplateFormat"].ToString();
            businessSMSContent = dt.Rows[1]["TemplateFormat"].ToString();
            maxFundingSMSContent = dt.Rows[2]["TemplateFormat"].ToString();
            maxFinanceSMSContent = dt.Rows[3]["TemplateFormat"].ToString();
            return personalSMSContent;
        }

    }
}
